package com.it.controller.admin;

import com.it.admin.AdminTypeService;
import com.it.bean.R;
import com.it.bean.RestStatusEnum;
import com.it.pojo.Type;
import com.it.pojo.params.BasePage;
import com.it.pojo.params.type.TypeEditQuery;
import com.it.pojo.vo.type.AdminTypeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/admin/type")
@Api(value = "v1", tags = "分类相关接口")

public class AdminTypeController {


    @Resource
    private AdminTypeService adminTypeService;

    @GetMapping("list")
    @ApiOperation(value = "查询所有分类", notes = "查询所有分类")
    public R<?> list() {
        List<AdminTypeVO> types = adminTypeService.listCategories();
        return R.success("成功", types);
    }


    @PostMapping("save")
    @ApiOperation(value = "新增分类", notes = "新增分类")
    public R<?> save(@RequestParam("typeName") String typeName) {
        if (StringUtils.isEmpty(typeName)) {
            return R.error(RestStatusEnum.PARAMS_ERROR);
        }
        System.out.println("typeName = " + typeName);
        return adminTypeService.insertType(typeName) > 0 ? R.success() : R.error();
    }

    @PostMapping("list")
    @ApiOperation(value = "查询分类", notes = "查询分类")
    public R<?> list(@RequestBody BasePage basePage) {
        Integer pageNum = basePage.getPageNum();
        Integer limit = basePage.getLimit();
        if (pageNum <= 0 || limit <= 0) {
            return R.error(RestStatusEnum.PARAMS_ERROR);
        }
        Map<String, Object> map = adminTypeService.listCategories(basePage);
        return R.success("成功", map);
    }

    @DeleteMapping("{typeId}")
    @ApiOperation(value = "删除分类", notes = "删除分类")
    public R<?> delete(@PathVariable("typeId") Integer typeId) {
        if (typeId == null) {
            return R.error(RestStatusEnum.PARAMS_ERROR);
        }
        return adminTypeService.deleteTypeById(typeId)
                > 0 ? R.success() : R.error();
    }

    @PutMapping("")
    @ApiOperation(value = "根据分类id修改分类信息", notes = "根据分类id修改分类信息")
    public R<?> edit(@RequestBody TypeEditQuery typeEditQuery) {
        if (typeEditQuery == null) {
            return R.error(RestStatusEnum.PARAMS_ERROR);
        }
        // TODO 参数校验不做
        Type type = new Type();
        BeanUtils.copyProperties(typeEditQuery, type);
        return adminTypeService.updateTypeById(type)
                > 0 ? R.success() : R.error();
    }

    @GetMapping("{typeId}")
    public R<?> getType(@PathVariable("typeId") Integer typeId) {
        if (typeId == null) {
            return R.error(RestStatusEnum.PARAMS_ERROR);
        }
        String rest = adminTypeService.getType(typeId);
        return R.success("成功", rest);
    }
}
